from ai_assistants import (
    AIAssistant, DataAnalysisAssistant, ImageGenerationAssistant,
    TextGenerationAssistant, TranslationAssistant, VoiceAssistant
)


class AIManager:
    """AI助手管理器，负责助手的存储与功能调度"""

    def __init__(self, max_size=20):
        self.max_size = max_size  # 固定数组大小（默认20）
        self.assistants = [None] * max_size  # 存储助手的数组
        self.current_count = 0  # 当前助手数量

    def get_assistant_by_id(self, aid):
        """根据ID查找助手（返回助手对象或None）"""
        for ass in self.assistants:
            if ass and ass.aid == aid:
                return ass
        return None

    def add_assistant(self, new_assistant):
        """添加新AI助手"""
        # 校验ID唯一性
        if self.get_assistant_by_id(new_assistant.aid):
            return False, f"❌ ID {new_assistant.aid} 已存在，添加失败！"
        # 校验数组是否已满
        if self.current_count >= self.max_size:
            return False, "❌ 系统容量已满，无法添加新助手！"

        # 插入数组（找第一个空位置）
        for i in range(self.max_size):
            if self.assistants[i] is None:
                self.assistants[i] = new_assistant
                self.current_count += 1
                return True, f"✅ 助手【{new_assistant.name}】添加成功！"

    def delete_assistant(self, aid):
        """根据ID删除助手"""
        ass = self.get_assistant_by_id(aid)
        if not ass:
            return False, f"❌ ID {aid} 不存在，删除失败！"

        # 从数组中移除（置为None）
        for i in range(self.max_size):
            if self.assistants[i] and self.assistants[i].aid == aid:
                self.assistants[i] = None
                self.current_count -= 1
                return True, f"✅ 助手【{ass.name}】已删除。"

    def get_all_assistants(self):
        """获取所有助手列表（过滤空值）"""
        return [ass for ass in self.assistants if ass is not None]

    def get_statistics(self):
        """获取系统统计信息"""
        all_ass = self.get_all_assistants()
        if not all_ass:
            return {
                "total": 0,
                "online": 0,
                "offline": 0,
                "avg_score": 0.0
            }
        online_count = sum(1 for ass in all_ass if ass.is_online)
        total_score = sum(ass.ability_score for ass in all_ass)
        avg_score = round(total_score / len(all_ass), 2)
        return {
            "total": len(all_ass),
            "online": online_count,
            "offline": len(all_ass) - online_count,
            "avg_score": avg_score
        }
